import VueRouter from "vue-router";
import Vue from "vue";
import routes from "@/routes/routes";
import store from "@/store";
Vue.use(VueRouter)
//重写$router.push方法
const OldRouterPush = VueRouter.prototype.push
VueRouter.prototype.push = function (
    location,
    onComplete=()=>{},
    onAbort=()=>{}){

    OldRouterPush.call(this,location,onComplete,onAbort)
}
//重写$router.replace方法
const OldRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (
    location,
    onComplete=()=>{},
    onAbort=()=>{}){

    OldRouterReplace.call(this,location,onComplete,onAbort)
}

const router = new VueRouter({
    mode:"history",
    routes
})
console.log(store)
const whitePath = ["login","home","register","search","detail","shopCart","addCartSuccess"]
router.beforeEach(async (to,from,next)=>{
    const token = store.state.user.token
    if(token){
        if(to.name === "login"){
            next("/home")
        }else {
            const isUserInfo = !!store.state.user.userInfo.nickName
            if(isUserInfo){
                next()
            }else {
                try {
                    await store.dispatch("user/getUserInfo")
                    next()
                }catch (e){
                    await store.dispatch("user/getRemove")
                    next(`/login?redirect=${to.name}`)
                }
            }
        }
    }else {
        if(whitePath.includes(to.name)){
            next()
        }else {
            next(`/login?redirect=${to.name}`)
        }
    }
})

export default router